import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @作者 ： opentestcase024 @时间 ： 2023/11/17
 * @测试点 : 并发getObject方法调用
 * @history: 优化连接超时参数为0; by opentestcase024
 **/

public class jdbc_set_get_object_case0015 {
	private static String URLstr;
	private static String USERNAME;
	private static String PASSWORD;
	private static String TABLENAME;
	private static int THREAD_NUM = 100;

	private static void executeGetobject() throws SQLException {
		Connection connection = null;
		try {
			connection = DriverManager.getConnection(URLstr, USERNAME, PASSWORD);
		} catch (SQLException s) {
			s.printStackTrace();
		}
		try {
			String sql = "select * from " + TABLENAME + " order by 1 desc ;";
			PreparedStatement ps_select = connection.prepareStatement(sql);
			ResultSet rs = ps_select.executeQuery();
			int idx = 0;
			while (rs.next()) {
				LocalDate result1 = rs.getObject(1, LocalDate.class);
				System.out.println("第" + idx + "行结果：" + result1);
				idx = idx + 1;
			}
			ps_select.close();

			sql = "select sysdate ;";
			PreparedStatement ps_time = connection.prepareStatement(sql);
			ResultSet rs1 = ps_time.executeQuery();
			while (rs1.next()) {
				String result = rs1.getString(1);
				System.out.println(result);
			}
			ps_time.close();

		} catch (SQLException s) {
			s.printStackTrace();
		}
		try {
			connection.close();
		} catch (SQLException s) {
			s.printStackTrace();
		}
	}

	private static void execute() {
		ExecutorService executorService = Executors.newFixedThreadPool(THREAD_NUM);
		for (int i = 0; i < THREAD_NUM; i++) {
			int finalI = i;
			executorService.submit(() -> {
				System.out.println("Start select thread {" + finalI + "}");
				try {
					executeGetobject();
				} catch (SQLException e) {
					e.printStackTrace();
					throw new RuntimeException(e);
				}
			});
		}
		executorService.shutdown();
		System.out.println("end excute");
	}

	public static void main(String[] args) throws SQLException {
		if (args.length < 6) {
			System.out.print("need para: host:ip,db_b,user,password,tablename,thread_num");
			return;
		}
		URLstr = "jdbc:postgresql://" + args[0] + "/" + args[1] + "?loggerLevel=off&socketTimeoutInConnecting=0";
		USERNAME = args[2];
		PASSWORD = args[3];
		TABLENAME = args[4];
		THREAD_NUM = Integer.parseInt(args[5]);
		execute();
	}
}
